<!-- Datatables -->
<link href="/vendors/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet">

<!-- page content -->
<div id="moduleList" class="right_col" role="main">
	<div class="">
		<div class="page-title">
			<div class="title_left">
				<h3>
					Users <small>list</small>
				</h3>
			</div>
		</div>
		
		<div class="clearfix"></div>
		
		<div class="row">
			<div class="col-md-12 col-sm-12 ">
				<div class="x_panel">
					<div class="x_title">
						<button type="button" class="btn btn-primary" @click="initAddModal()" 
							data-toggle='modal' data-target='#addModal'>新增</button>
						<div class="clearfix"></div>
					</div>
					<div class="x_content">
						<div class="row">
							<div class="col-sm-12">
								<div class="card-box table-responsive">
									<table id="moduleTable" class="table table-striped table-bordered" style="width: 100%">
										<thead>
											<tr>
												<th>Id</th>
												<th>User Name</th>
												<th>Email</th>
												<th>Password</th>
												<th>Create Date</th>
												<th>Operation</th>
											</tr>
										</thead>
										<tbody></tbody>
									</table>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	
	<!-- 碎片文件要放在 Vue 控制的 Div 里 -->
	<div th:replace="account/userAdd"></div>
	<div th:replace="account/userEdit"></div>
</div>
<!-- /page content -->

<!-- Datatables -->
<script src="/vendors/datatables.net/js/jquery.dataTables.min.js" stype="text/javascript"></script>
<script src="/vendors/datatables.net-bs/js/dataTables.bootstrap.min.js" stype="text/javascript"></script>

<script stype="text/javascript">
	var users = new Vue({
		el: "#moduleList",
		data: {
			defaultPageSize: 5,
			moduleTable: {},
			user: {
				id: "",
				email: "",
				userName: "",
				password: "",
				userImage: "",
				createDate: "",
				roles: [],
			},
			allRoles: [],
		},
		methods: {
			// 表格行数据结构
			RowData: function (id, email, userName, password, userImage, createDate) {
				var RowData = {};
				RowData.id = id;
				RowData.email = email;
				RowData.userName = userName;
				RowData.password = password;
				RowData.userImage = userImage;
				RowData.createDate = createDate;
				RowData.operate = function () {
					return "<a href='#' class='btn_editcolor' data-toggle='modal' data-target='#editModal' " + 
						"onclick='initEditModal(\"" + id + "\")'>编辑</a>&nbsp;" + 
						"<a href='javascript:void(0);' onclick='deleteModule(\"" + id + 
						"\")' class='btn_editcolor'>删除</a>";
				};
				return RowData;
			},
			initTable: function (pageSize) {
				var self = this;
				self.moduleTable = $('#moduleTable').DataTable({
					'paging': true, //分页
					"serverSide": true, //开启后端分页
					"pagingType": "full_numbers", //分页样式的类型simple/simple_numbers/full/full_numbers
					"pageLength": pageSize, //定义初始的页长
					"processing": true, 
					"destroy": true, //允许销毁替换，在表格重新查询时，可以自动销毁以前的data
					'lengthChange': true, //控制是否能够调整每页的条数
					'lengthMenu': [5, 10, 25, 50], // 控制页长
					'searching': true,
					'data-show-refresh': true,
					'ordering': true,
					'autoWidth': false,
					"ajax": function (data, callback, settings) {
						// 从data获取查询数据
						var columIndex = data.order[0].column;
						var direction = data.order[0].dir;
						var orderBy = data.columns[columIndex].name;
						pageSize = data.length == undefined  ? pageSize : data.length;
						
						var searchBean = {};
						searchBean.currentPage = (data.start / pageSize) + 1;
						searchBean.pageSize = pageSize;
						searchBean.orderBy = orderBy;
						searchBean.direction = direction;
						searchBean.keyWord = data.search.value;
						
						$.ajax({
							url : "/api/users",
							type : "post",
							contentType: "application/json",
							data : JSON.stringify(searchBean),
							success : function (rs) {
								// 定义表格数据结构
								var tableData = {
									draw :0,
									recordsTotal: 0,
									recordsFiltered: 0,
									data: []
								};
								if (!rs) {
									layer.alert("请求出错，请稍后重试" + rs.errmsg, {icon: 2});
									callback(tableData);
									return;
								};
								if (rs.list == null) {
									$('#moduleTable tbody tr').remove();
									$('#loading').remove();
									callback(tableData);
									return;
								}
								$('#loading').remove();
								var rowsData = [];
								for (var i = 0; i < rs.list.length; i++) {
									//包装行数据
									var rowData = self.RowData(rs.list[i].id, rs.list[i].email, rs.list[i].userName, 
											rs.list[i].password, rs.list[i].userImage, rs.list[i].createDate);
									// 将行数据放到数组里
									rowsData.push(rowData);
								}
								tableData.data = rowsData;
								tableData.recordsTotal = rs.total;
								tableData.recordsFiltered = rs.total;
								callback(tableData);
							},
							error : function (data) {
								layer.alert(data.responseText, {icon: 0});
							}
						});
					},
					"columns": [ //定义行数据字段
						{data: 'id', name: "id", sortable: true}, 
						{data: 'email', name: "email", sortable: true}, 
						{data: 'userName', name: "user_name", sortable: true}, 
						{data: 'password', name: "password", sortable: true}, 
						{data: 'createDate', name: "create_date", sortable: true}, 
						{data: 'operate', width: '80px', sortable: false}
					]
				});
			},
			initRoles: function () {
				var self = this;
				$.ajax({
					url : "/api/roles",
					type : "get",
					success : function (rs) {
						self.allRoles = rs;
					},
					error : function (data) {
						layer.alert(data.responseText, {icon: 0});
					}
				});
			},
			initAddModal: function () {
				this.user = {
					id: "",
					email: "",
					userName: "",
					password: "",
					userImage: "",
					createDate: "",
					roles: [],
				};
			},
			addModule: function () {
				this.user.roles = this.user.roles.map(
						item => {var role = {}; role.id = item; return role;});
				var self = this;
				$.ajax({
					url : "/api/user",
					type : "post",
					contentType: "application/json",
					data : JSON.stringify(self.user),
					success : function (rs) {
						if (rs.status == 200) {
							self.initTable(self.defaultPageSize);
						} else {
							layer.msg(rs.message, {icon: 0});
						}
					},
					error : function (rs) {
						layer.msg(rs.responseText, {icon: 0});
					}
				});
			},
			initEditModal: function (id) {
				var self = this;
				$.ajax({
					url : "/api/user/" + id,
					type : "get",
					contentType: "application/json",
					success : function (rs) {
						self.user = rs;
						self.user.roles = self.user.roles.map(item => item.id);
					},
					error : function (data) {
						layer.alert(data.responseText, {icon: 0});
					}
				});
			},
			editModule: function () {
				var self = this;
				self.user.roles = self.user.roles.map(
						item => {var role = {}; role.id = item; return role;});

				$.ajax({
					url : "/api/user",
					type : "put",
					contentType: "application/json",
					data : JSON.stringify(self.user),
					success : function (rs) {
						if (rs.status == 200) {
							self.initTable(self.defaultPageSize);
						} else {
							layer.msg(rs.message, {icon: 0});
						}
					},
					error : function (rs) {
						layer.msg(rs.responseText, {icon: 0});
					}
				});
			},
			deleteModule: function (id) {
				var self = this;
				bootbox.confirm("Are you sure?", function(result) {
					if(result) {
						$.ajax({
							url : "/api/user/" + id,
							type : "delete",
							success : function (rs) {
								if (rs.status == 200) {
									self.initTable(self.defaultPageSize);
								} else {
									window.location.href = rs.data;
									// layer.msg(rs.message, {icon: 0});
								}
							},
							error : function (rs) {
								layer.msg(rs.responseText, {icon: 0});
							}
						});
					}
				});
			},
		},
		created: function () {
			// 将 Vue 的方法赋值给 window 对象，以解决动态生成 Html 不能解析 @click 标签的问题
			window.initEditModal = this.initEditModal;
			window.deleteModule = this.deleteModule;
		},
		mounted: function () {
			this.initTable(this.defaultPageSize);
			this.initRoles();
		}
	});
</script>